package com.xiang.utils.aggs;


import com.xiang.config.EsConfig;
import com.xiang.utils.CreateDoc;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.ExtendedStats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 平均数
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class ExtendedStatsQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * 聚合统计查询最小最大
     */
    @Test
    public void extendedStats() throws IOException {
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.extendedStats("age").field("age"));
        request.source(builder);
        // 执行查询
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        ExtendedStats age = res.getAggregations().get("age");
        double max = age.getMax();
        double min = age.getMin();
        double sum = age.getSum();
        logger.info("最大年龄：{}，最小年龄：{}，年龄总和：{}", max, min, sum);
    }
}
